import { useTokenStore } from '../stores/token.js'
import request from '../utils/request.js'

// 获取所有帖子
export const communityService = (params) => {
    const tokenStore = useTokenStore()
    return request.get('/community/post/all', { 
        headers: { 'Authorization': tokenStore.token }, 
        params: params 
    })
}

// 更新帖子
export const updatePost = (post) => {
    const tokenStore = useTokenStore();
    return request.post('/community/post/update', 
        post,
        { headers: { 'Authorization': tokenStore.token } }
    );
}

// 删除帖子
export const deletePost = (postId) => {
    const tokenStore = useTokenStore();
    return request.delete(`/community/post/delete/${postId}`, {
        headers: { 'Authorization': tokenStore.token }
    });
}

// 获取帖子详情
export const getPostDetail = (postId) => {
    const tokenStore = useTokenStore();
    return request.get(`/community/post/detail/${postId}`, {
        headers: { 'Authorization': tokenStore.token }
    });
}

// 获取当前用户的帖子
export const getUserPosts = () => {
    const tokenStore = useTokenStore();
    return request.get('/community/post/allmypost', {
        headers: { 
            'Authorization': tokenStore.token,
            'Content-Type': 'application/json'
        }
    }).then(response => {
        console.log('API响应:', response); // 添加日志
        if (response.code === 0 && response.data) {
            return response;
        } else {
            throw new Error(response.msg || '获取帖子失败');
        }
    }).catch(error => {
        console.error('API错误:', error);
        throw error;
    });
}

// 获取最热帖子（按点赞量排序）
export const getHotPosts = (params) => {
    const tokenStore = useTokenStore();
    return request.get('/community/post/hot', {
        headers: { 'Authorization': tokenStore.token },
        params: params
    });
}